package com.usian.controller;

import com.usian.CookieUtils;
import com.usian.JsonUtils;
import com.usian.Result;
import com.usian.feign.CartFeign;
import com.usian.feign.ItemFeign;
import com.usian.pojo.TbItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RequestMapping("/frontend/cart/")
@RestController
public class CartController {


    @Autowired
    private ItemFeign itemFeign;

    @Autowired
    private CartFeign cartFeign;



    /**
     * 添加购物车
     *
     * @param userId
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("addItem")
    public Result addItem(String userId, Long itemId,
                          @RequestParam(defaultValue = "1") Integer num, HttpServletRequest request, HttpServletResponse response){
        //0: 判断用户是否登录
        if(StringUtils.isBlank(userId)){
             //未登录
             //1：查询购物车 map<itemId, tbitem>
            Map<String, TbItem> itemMap = this.getCartFromCookie(request);

            //2: 购物车添加   有  改num数量   没有   map  put
            this.addItemToCart(itemMap,itemId,num);

            //3：map购物车  添加到cookie
            this.addClientCookie(request,response,itemMap);

            return Result.ok();

        }else{
            //已登录
            //1：查询购物车
            Map<String, TbItem> carts = this.getCartFromRedis(userId);
            //2:添加购物车
            this.addItemToCart(carts,itemId,num);
            //3：map购物车  添加到redis
            boolean result = this.addClientRedis(carts, userId);
            if(result){
                return Result.ok();
            }
        }
        return Result.error("添加购物车失败");
    }

    /**
     * 查询cookie中的购物车信息
     *
     * @param request
     * @return
     */
    private Map<String, TbItem>  getCartFromCookie(HttpServletRequest request){
        Map<String, TbItem> map =new HashMap<>();
        String cartString = CookieUtils.getCookieValue(request,"CART_COOKIE_KEY",true);
        if(StringUtils.isNotBlank(cartString)){
            map= JsonUtils.jsonToMap(cartString, TbItem.class);
            return map;
        }
        return  map;
    }

    /**
     * 询redis中的购物车信息
     *
     * @param userId
     * @return
     */
    private Map<String, TbItem>  getCartFromRedis(String userId){

        Map<String,TbItem> cart = cartFeign.selectCartByUserId(userId);
        if(cart!=null && cart.size()>0){
            return cart;
        }
        return new HashMap<String,TbItem>();
    }

    /**
     * 添加购物车
     * @param cart
     * @param itemId
     * @param num
     */
    private void  addItemToCart(Map<String, TbItem> cart,Long itemId,Integer num){
            TbItem tbItem = cart.get(itemId.toString());
            if(tbItem !=null){
                //  购物车以前的数量累加
                tbItem.setNum(tbItem.getNum()+num);
            }else{
                tbItem = itemFeign.selectItemInfo(itemId);
                tbItem.setNum(num);
            }
            cart.put(itemId.toString(),tbItem);
    }

    /**
     * 购物车加到cookie
     * @param request
     * @param response
     * @param cart
     */
    private void addClientCookie(HttpServletRequest request,HttpServletResponse response,Map<String, TbItem> cart){
        String cartString = JsonUtils.objectToJson(cart);
        CookieUtils.setCookie(request,response,"CART_COOKIE_KEY",cartString,true);
    }

    /**
     * 购物车加到redis
     * @param cart
     * @param userId
     * @return
     */
    private boolean addClientRedis(Map<String, TbItem> cart,String userId){
         boolean bool = cartFeign.insertItemToRedis(cart,userId);
        return bool;
    }


    /**
     * 查询购物车
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("showCart")
    public Result showCart(String userId,HttpServletRequest request){
        List<TbItem>  list=new ArrayList<>();

        if(StringUtils.isBlank(userId)){
            //未登录  3
            Map<String, TbItem> carts = this.getCartFromCookie(request);

            Set<String> keySet = carts.keySet();
            for(String key :keySet){
                TbItem tbItem = carts.get(key);
                list.add(tbItem);
            }
            return Result.ok(list);

        }else{
            //已登录

            //1：查询购物车  redis
            Map<String, TbItem> carts = this.getCartFromRedis(userId);

            //2: 遍历map 购物车  存放到list
            Set<String> keySet = carts.keySet();
            for(String key :keySet){
                TbItem tbItem = carts.get(key);
                list.add(tbItem);
            }
            return Result.ok(list);
        }
    }

    /**
     * 修改购物车 修改数量
     *
     * @param userId
     * @param itemId
     * @param num
     * @param request
     * @return
     */
    @RequestMapping("updateItemNum")
    public Result  updateItemNum(String userId,Long itemId,Integer num,
                                 HttpServletRequest request,HttpServletResponse response){

        if(StringUtils.isBlank(userId)){
            //未登录
            Map<String, TbItem> carts = this.getCartFromCookie(request);

            TbItem tbItem = carts.get(itemId.toString());
            tbItem.setNum(num);

            carts.put(itemId.toString(),tbItem);

            this.addClientCookie(request,response,carts);

            return Result.ok();
        }else{
            //已登录
            //1:查询购物车从redis

            Map<String, TbItem> carts = this.getCartFromRedis(userId);
            System.out.println(carts.get("161104658164126"));
            //2:修改购物车中的数量
            System.out.println(itemId.toString());
            TbItem tbItem = carts.get(itemId.toString());
            tbItem.setNum(num);

            carts.put(itemId.toString(),tbItem);
            //3:重写到redis
            this.addClientRedis(carts,userId);

            return Result.ok();
        }
    }


    /**
     * 删除购物车
     *
     * @param userId
     * @param itemId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(String userId,Long itemId,HttpServletRequest request,HttpServletResponse response){
        if(StringUtils.isBlank(userId)){
            //未登录
            //查询购物车列表
            Map<String, TbItem> carts = this.getCartFromCookie(request);

            //map 删除其中指定key 的元素
            carts.remove(itemId.toString());

            //写入cookie
            this.addClientCookie(request,response,carts);

            return Result.ok();
        }else{
            //已登录
            //查询购物车列表
            Map<String, TbItem> carts = this.getCartFromRedis(userId);

            //map 删除其中指定key 的元素
            carts.remove(itemId.toString());

            //写入redis
            this.addClientRedis(carts,userId);

            return Result.ok();
        }
    }




}
